<template>
	<view>
		<view>
			<video :src="url" ref="myVideo" id="myVideo" :initial-time="currentData.watchTime" @timeupdate="ontimeupdate" controls
				style="width: 100%;" @loadedmetadata="loadedmetadata" @play="onplay" @pause="onpause" @ended="onended"></video>
		</view>
		<PopupVerification :time="60*10" @open="stopPlay"/>
		<!-- <view>
			<text>
				{{watchTime}}
			</text>
		</view> -->
	</view>
</template>

<script>
	import PopupVerification from '@/components/PopupVerification/index.vue'
	import dayjs from 'dayjs'
	import {
		courselogDetail,
		upDataTime
	} from '@/api/training.js'
	export default {
		data() {
			return {
				url: '',
				currentData: null,
				upDataTime: {
					startTime: 0,
					endTime: 0,
					currentTime: 0
				},
				watchTime: 0,
				videoContext: null,
			}
		},
		components:{
			PopupVerification
		},
		onLoad({
			url,
			watchTime
		}) {
			uni.showLoading({
				mask:true,
				title: '加载中'
			})
			this.watchTime = watchTime;
			this.url = url;
			this.currentData = {
				...uni.getStorageSync('Course'),
				userId: uni.getStorageSync('userInfo').id
			}
			this.videoContext = uni.createVideoContext('myVideo',this)
		},
		methods: {
			loadedmetadata() {
				uni.hideLoading()
				setTimeout(()=>{
					this.setWatchTime()
				},1000)
			},
			setWatchTime(){
				let position =  this.watchTime || 0;
				this.videoContext.seek(position)
			},
			stopPlay() {
			  if (this.videoContext) {
				this.videoContext.play()
				// this.videoContext.pause()
			  }
			},
			ontimeupdate({
				detail
			}) {
				this.upDataTime.currentTime = detail.currentTime
			},
			onplay(e) {
				this.upDataTime.startTime = dayjs().valueOf()
			},
			onpause(e) {
				this.putDataTime()
			},
			onended(e) {
				this.putDataTime()
			},
			async putDataTime() {
				
				if(!this.upDataTime.startTime){
					return
				}
				
				this.upDataTime.endTime = dayjs().valueOf()

				const data = {
					elCourseId: this.currentData.elCourseId,
					elTrainId: this.currentData.elTrainId,
					userId: this.currentData.userId,

					startTime: dayjs(this.upDataTime.startTime).format('YYYY-MM-DD HH:mm:ss'),
					endTime: dayjs(this.upDataTime.endTime || dayjs()).format('YYYY-MM-DD HH:mm:ss'),

					totalDuration: Math.floor(((this.upDataTime.endTime || dayjs().valueOf()) - this
						.upDataTime
						.startTime) / 1000),
					watchTime: Math.floor(this.upDataTime.currentTime)
				}
				if(
					data.elCourseId 
					&& data.elTrainId
					&& data.userId
				){
					upDataTime(data)
					this.clearData()
				}
				
			},
			clearData() {
				this.upDataTime = {
					startTime: 0,
					endTime: 0,
					currentTime: 0
				}
			}
		},
		destroyed() {
			this.putDataTime()
		},

	}
</script>